# -*- coding: utf-8 -*-
"""
Created on Fri Sep  9 11:35:48 2022

@author: wulong
"""
'tag = 1 indicates this is first time of iteration'
'data comes from last time step'
'tag != 1 indicates this is not first time of iteration'
'data comes from last iterative step'

import numpy as np
from casadi import *
from Fast_2_formulate_Opt import *
from Obtain_results import *
from Transfer_fast import *

def F2_EMPC(initial_state, state_guess, state_bnds_lo, state_bnds_up,
            slow_state_bnds, fast_1_state_bnds, fast_3_state_bnds,
            slow_input_bnds, fast_1_input_bnds, fast_3_input_bnds,
            input_guess, input_bnds_lo, input_bnds_up,
            input_bin_bnds,
            distb_bnds,
            output_guess, output_bnds_lo, output_bnds_up,
            fast_state_setpnts, fast_input_setpnts,
            alpha, alpha_xf, alpha_uf, pred_horzn,
            pf, pmg, pse,
            tag, pred_horzn_fast_1, pred_horzn_fast_3, X_int_f1, X_int_f3, 
            i, del_Uc, past_Uc, past_Uz,
            alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq,
            pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
            pcm, ppn, rxi, rxi_as, yeb):
    
    f1_x_u = fast_x_u(pred_horzn, pred_horzn_fast_1,
                      fast_1_state_bnds, fast_1_input_bnds, tag, i)
    fast_1_state_bnds_new = f1_x_u[0]
    fast_1_input_bnds_new = f1_x_u[1]
    
    f3_x_u = fast_x_u(pred_horzn, pred_horzn_fast_3,
                      fast_3_state_bnds, fast_3_input_bnds, tag, i)
    fast_3_state_bnds_new = f3_x_u[0]
    fast_3_input_bnds_new = f3_x_u[1]
    
    f_opt = formulate_opt_f2(initial_state, state_guess, state_bnds_lo, state_bnds_up,
                             slow_state_bnds, fast_1_state_bnds_new, fast_3_state_bnds_new,
                             slow_input_bnds, fast_1_input_bnds_new, fast_3_input_bnds_new,
                             input_guess, input_bnds_lo, input_bnds_up,
                             input_bin_bnds,
                             distb_bnds,
                             output_guess, output_bnds_lo, output_bnds_up,
                             fast_state_setpnts, fast_input_setpnts,
                             alpha, alpha_xf, alpha_uf, pred_horzn,
                             pf, pmg, pse, X_int_f1, X_int_f3,
                             i, del_Uc, past_Uc, past_Uz,
                             alpha_ue, Uc_nb, It_d_Uc, Uc_it_sq, tag,
                             pre_d_Uc, pre_sq_Uc, pre_sq_Uz,
                             pcm, ppn, rxi, rxi_as, yeb)
    
    s_opt = solve_opt_f2(*f_opt)
    
    r_opt = get_results_f2(s_opt[0], pred_horzn)
    
    J = s_opt[1]
    
    return r_opt, J
